<template>
  <div class="card">
    <div class="flex justify-between items-center">
      <h2 class="text-lg font-bold">消费市场（限额以上）</h2>
      <div class="text-sm text-gray-500">单位：亿元</div>
    </div>

    <div class="relative chart-container bg-white rounded-lg shadow p-2 pb-5">
      <!-- 显示各行业全年综合 -->
      <div class="mb-2">
        <span v-for="(dataset, index) in formattedChartData.datasets" :key="index" class="mr-4">
          {{ dataset.label }}:<span class="font-bold">{{ getTotal(dataset.data) }}</span>
        </span>
      </div>
      <LineChart
        :data="formattedChartData"
        :options="chartOptions"
        class="w-full h-full chart-container"
      />
      <!-- 数据卡片悬浮层 -->
      <div
        v-if="hoverData"
        class="absolute bg-white rounded-lg shadow-lg p-3 z-10 transition-opacity duration-200"
        :style="{ left: hoverData.x + 'px', top: hoverData.y + 'px' }"
      >
        <div class="font-semibold text-sm text-gray-800">{{ hoverData.label }}</div>
        <div class="flex items-center mt-1">
          <span
            class="inline-block w-2 h-2 rounded-full mr-1"
            :style="{ backgroundColor: hoverData.color }"
          ></span>
          <span class="text-xs text-gray-600"
            >{{ hoverData.datasetLabel }}: {{ hoverData.value }}</span
          >
        </div>
      </div>
      <!-- 手动添加预测数据注释（替代annotation插件） -->
      <div v-if="showPredictionNote" class="absolute bottom-8 right-4 text-xs text-gray-500">
        <span class="inline-block w-3 h-1 bg-gray-400 mr-1" :style="{ borderDash: '5,5' }"></span>
        预测数据
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  Chart as ChartJS,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'
import { number } from 'echarts'

// 注册Chart.js组件（移除Annotation）
ChartJS.register(LinearScale, PointElement, LineElement, Title, Tooltip, Legend)

// 预测函数：基于历史数据生成线性预测值
const predictData = (historicalData) => {
  const n = historicalData.length
  if (n < 2) return 0

  let sumX = 0,
    sumY = 0,
    sumXY = 0,
    sumX2 = 0
  historicalData.forEach((val, idx) => {
    sumX += idx + 1
    sumY += val
    sumXY += (idx + 1) * val
    sumX2 += (idx + 1) * (idx + 1)
  })

  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n
  return slope * (n + 1) + intercept
}

// 原始历史数据（2021-2024年）
const rawHistoricalData = {
  labels: ['2021年', '2022年', '2023年', '2024年'],
  datasets: [
    {
      label: '批发业',
      data: [140, 160, 145, 170],
      borderColor: '#165DFF',
      backgroundColor: 'rgba(22, 93, 255, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#165DFF',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '零售业',
      data: [95, 105, 120, 110],
      borderColor: '#FF7D00',
      backgroundColor: 'rgba(255, 125, 0, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#FF7D00',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '住宿业',
      data: [35, 40, 45, 50],
      borderColor: '#00B42A',
      backgroundColor: 'rgba(0, 180, 42, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#00B42A',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
    {
      label: '餐饮业',
      data: [45, 55, 60, 70],
      borderColor: '#F53F3F',
      backgroundColor: 'rgba(245, 63, 63, 0.1)',
      borderWidth: 2.5,
      tension: 0.3,
      fill: true,
      pointBackgroundColor: '#fff',
      pointBorderColor: '#F53F3F',
      pointBorderWidth: 2,
      pointRadius: 4,
      pointHoverRadius: 6,
    },
  ],
}

const hoverData = ref(null)
const showPredictionNote = ref(false)

// 生成带预测数据的完整数据集
const formattedChartData = computed(() => {
  const fullData = {
    ...rawHistoricalData,
    labels: [...rawHistoricalData.labels, '2025年(预测)'],
    datasets: rawHistoricalData.datasets.map((dataset) => {
      const predictedValue = Number(predictData(dataset.data).toFixed(2))

      return {
        ...dataset,
        data: [...dataset.data, predictedValue],
        // 预测数据使用虚线（前4段实线，最后1段虚线）
        borderDash: [0, 0, 0, 0, 5, 5],
        // 预测点使用菱形标记
        pointStyle: (context) => (context.dataIndex === dataset.data.length ? 'diamond' : 'circle'),
        pointBackgroundColor: (context) =>
          context.dataIndex === dataset.data.length ? dataset.borderColor : '#fff',
        pointBorderColor: (context) =>
          context.dataIndex === dataset.data.length ? '#fff' : dataset.borderColor,
        pointBorderWidth: 2,
        pointRadius: (context) => (context.dataIndex === dataset.data.length ? 6 : 4),
      }
    }),
  }
  return fullData
})

const chartOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top',
      labels: {
        usePointStyle: true,
        boxWidth: 6,
        color: '#666',
        font: { size: 11 },
        padding: 15,
        // 添加预测数据图例说明
        callbacks: {
          label: (context) => {
            if (context.dataIndex === context.dataset.data.length - 1) {
              return `${context.dataset.label} (预测)`
            }
            return context.dataset.label
          },
        },
      },
    },
    tooltip: {
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      titleColor: '#333',
      bodyColor: '#666',
      borderColor: 'rgba(0, 0, 0, 0.05)',
      borderWidth: 1,
      padding: 10,
      boxPadding: 5,
      usePointStyle: true,
      callbacks: {
        label: (context) => {
          const isPredicted = context.dataIndex === context.dataset.data.length - 1
          return ` ${context.dataset.label}: ${context.raw}${isPredicted ? ' (预测)' : ''}`
        },
      },
      external: (context) => {
        const tooltip = context.tooltip
        if (tooltip.opacity === 0 || !context.dataPoints || context.dataPoints.length === 0) {
          hoverData.value = null
          return
        }

        const dataPoint = context.dataPoints[0]
        const position = context.chart.canvas.getBoundingClientRect()
        const isPredicted = dataPoint.dataIndex === dataPoint.dataset.data.length - 1

        hoverData.value = {
          x: position.left + tooltip.caretX,
          y: position.top + tooltip.caretY,
          label: tooltip.title[0] + (isPredicted ? ' (预测)' : ''),
          value: dataPoint.raw,
          datasetLabel: dataPoint.dataset.label,
          color: dataPoint.dataset.borderColor,
        }

        // 显示预测数据注释
        showPredictionNote.value = isPredicted
      },
    },
  },
  scales: {
    x: {
      grid: { display: false },
      ticks: {
        color: '#999',
        font: { size: 11 },
        maxRotation: 0,
        minRotation: 0,
      },
    },
    y: {
      beginAtZero: true,
      grid: { color: 'rgba(0, 0, 0, 0.05)', drawBorder: false },
      ticks: {
        color: '#999',
        font: { size: 11 },
        padding: 15,
        callback: (value) => value + '亿',
      },
    },
  },
  interaction: { mode: 'index', intersect: false },
  animation: { duration: 1000, easing: 'easeOutQuart' },
}))

// 计算数组总和
const getTotal = (arr) => arr.reduce((acc, cur) => acc + cur, 0)
</script>

<style scoped>
.chart-container {
  padding-bottom: 20px;
}
.card {
  overflow: hidden;
}
.chart-container {
  height: 200px;
}
/* 自定义虚线样式 */
[style*='borderDash'] {
  display: inline-block;
  border-top: 1px solid currentColor;
  border-style: dashed;
  transform: rotate(90deg);
  transform-origin: center;
  margin-top: 2px;
}
</style>
